package com.bosssoft.platform.fasttcc.support;

import com.bosssoft.platform.fasttcc.CompleteStageListener;
import com.bosssoft.platform.fasttcc.RemoteResource;
import com.bosssoft.platform.fasttcc.RemoteResourceFactory;
import com.bosssoft.platform.fasttcc.Xid;
import com.jfireframework.baseutil.StringUtil;
import com.jfireframework.baseutil.TRACEID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrlConnectionRemoteResourceFactory extends CachedRemoteResourceFactory
{
    static final         String NODEIDENTIFIER = "FASTTCC-NODEIDENTIFIER";
    private static final Logger LOGGER         = LoggerFactory.getLogger(HttpUrlConnectionRemoteResourceFactory.class);
    private final        String identifier;

    public HttpUrlConnectionRemoteResourceFactory(String identifier)
    {
        this.identifier = identifier;
    }

    @Override
    protected RemoteResource build(String identifier)
    {
        return new HttpRemoteResource(identifier);
    }

    class HttpRemoteResource extends AbstractRemoteResource
    {

        public HttpRemoteResource(String identifier)
        {
            super(identifier);
        }

        private boolean doRequest(String url, CompleteStageListener listener)
        {
            String traceId = TRACEID.newTraceId();
            LOGGER.debug("traceId:{} 准备发起远端提交请求，url:{}", traceId, url);
            try
            {
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                connection.addRequestProperty(NODEIDENTIFIER, HttpUrlConnectionRemoteResourceFactory.this.identifier);
                connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                connection.connect();
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                {
                    return false;
                }
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String         lines;
                while ((lines = reader.readLine()) != null)
                {
                    ;
                }
                reader.close();
                // 断开连接
                connection.disconnect();
                if (lines.equals("success"))
                {
                    LOGGER.debug("traceId:{} 远端响应TCC请求成功", traceId);
                    listener.onRemoteFinish(this, true);
                    return true;
                }
                else
                {
                    LOGGER.debug("traceId:{} 远端响应TCC请求失败", traceId);
                    listener.onRemoteFinish(this, false);
                    return false;
                }
            }
            catch (IOException e)
            {
                LOGGER.error("traceId:{} 远端响应TCC请求失败", traceId, e);
                listener.onRemoteFinish(this, false);
                return false;
            }
        }

        @Override
        public void commit(boolean async, Xid xid, CompleteStageListener listener)
        {
            doRequest(commitUrlPrefix + xid.toString(), listener);
        }

        @Override
        public void rollback(boolean async, Xid xid, CompleteStageListener listener)
        {
            doRequest(rollbackUrlPrefix + xid.toString(), listener);
        }
    }
}
